package 数组题目.数组求和;

// 两数之和
// https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/
class 有序两数之和 {
    // 二分查找
    /*public int[] twoSum(int[] numbers, int target) {
        int[] ans = new int[2];
        for (int i = 0; i < numbers.length; i++) {
            int T = target - numbers[i];
            int l = i, r = numbers.length - 1;
            while (l <= r) {
                int mid = (l + r) / 2;
                if (numbers[mid] == T) {
                    if (mid == i) {
                        if (mid == 0) {
                            mid = mid + 1;
                        } else {
                            mid = numbers[mid - 1] + numbers[i] == target ? mid - 1 : mid + 1;
                        }
                    }
                    ans[0] = i + 1;
                    ans[1] = mid + 1;
                    return ans;
                }
                if (numbers[mid] > T) {
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            }
        }
        return ans;
    }*/
    // 双指针
    public int[] twoSum(int[] numbers, int target) {
        // 一个左一个右，如果左+右的值 > target 右边移动，反之左边移动
        int left = 0, right = numbers.length - 1;
        while (left < right) {
            if (numbers[left] + numbers[right] == target) {
                return new int[]{left + 1, right + 1};
            }
            if (numbers[left] + numbers[right] < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[2];
    }

//    public static void main(String[] args) {
//        TwoSum twoSum = new TwoSum();
//        System.out.println(twoSum.twoSum(new int[]{2, 7, 11, 15}, 9));
//    }
}
